import { ref, watch, watchEffect } from 'vue'
import { Action, ActionDetail, Field, Table } from '../moduleDetailType'
import { formRequiredIsFilled } from '@/utils'
import { ElMessageBox } from 'element-plus'

export default function useActionMethods () {
  const formDataActionDetail = ref<ActionDetail>({
    rawScript: '',
    saveScript: '',
    actionType: ''
  })

  const formDataAction = ref<Action>({
    name: '',
    type: '',
    before: '',
    after: '',
    label: '',
    detail: formDataActionDetail.value,
    id: 0,
    shell: ''
  })

  /**
   * 添加操作
   *
   * 当操作列表为空时，会添加一个默认的操作，并激活第一个表单项。
   * 当操作列表不为空时，会先验证当前表单是否已经填写完成，如果填写完成，则添加一个新的操作。
   */
  function addAction () {
    let m = new Date().getTime()
    if (actionList.value.length == 0 || !actionFormRef.value) {
      actionList.value.push({
        name: 'action' + m,
        label: '',
        type: '',
        before: '',
        after: '',
        detail: {
          rawScript: '',
          saveScript: '',
          actionType: ''
        },
        id: new Date().getTime(),
        shell: ''
      })
      actionItemActive.value = m // 激活最新的表单项
      formDataAction.value = actionList.value[actionList.value.length - 1]
    } else {
      actionFormRef.value && actionFormRef.value.validate()
      //  先验证当前表单是否已经填写完成
      let isFilled = formRequiredIsFilled(actionFormRules, formDataAction.value)

      if (isFilled) {
        let m = new Date().getTime()
        actionList.value.push({
          name: 'action' + m,
          label: '',
          type: '',
          before: '',
          after: '',
          detail: {
            rawScript: '',
            saveScript: '',
            actionType: ''
          },
          id: new Date().getTime(),
          shell: ''
        })
        actionItemActive.value = m // 激活最新的表单项
        formDataAction.value = actionList.value[actionList.value.length - 1]
      }
    }
  }

  /**
   * 删除动作
   *
   * @param item 要删除的动作对象
   */
  function deleteAction (item: any) {
    ElMessageBox.confirm('确定删除该方法吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(() => {
        if (item.id == actionItemActive.value) {
          actionItemActive.value = -1
          resetActionForm()
        }
        actionList.value = actionList.value.filter(i => i.id != item.id)
        // 删除之后自动选择上一个action
        if (actionList.value.length > 0) {
          actionItemActive.value =
            actionList.value[actionActiveIndex.value - 1].id
        }
      })
      .catch(() => {
        // 取消删除
      })
  }

  function resetActionForm () {
    formDataAction.value = {
      id: 0,
      label: '',
      name: '',
      type: '',
      before: '',
      after: '',
      detail: {
        rawScript: '',
        saveScript: '',
        actionType: ''
      },
      shell: ''
    }
  }
  const actionList = ref<Array<Action>>([])
  const actionItemActive = ref(
    actionList.value.length == 0 ? -1 : actionList.value[0].id
  )

  const actionFormRef = ref()
  const actionFormRules = {
    name: [{ required: true, message: '请输入方法名称', trigger: 'blur' }],
    // label: [{ required: true, message: '请输入方法标签', trigger: 'blur' }],
    type: [{ required: true, message: '请选择方法类型', trigger: 'change' }],
    // 'detail.saveScript': [
    //   { required: true, message: '请编辑方法详情', trigger: 'change' }
    // ],
    // shell:[
    //   { required: true, message: '请输入自定义脚本',  }
    // ]
  } as any

  /**
   * 选择操作项
   *
   * @param from 操作来源编号
   * @param item 操作项对象
   */
  function selectActionItem (from: number, item: any) {
    actionFormRef.value && actionFormRef.value.validate()
    let isFilled = formRequiredIsFilled(actionFormRules, formDataAction.value)
    if (!isFilled && from != -1) {
      return
    } else {
      actionItemActive.value = item.id
      formDataAction.value = item
    }
  }
  const actionActiveIndex = ref(0)
  watch(
    () => actionItemActive.value,
    (val: any) => {
      actionActiveIndex.value = actionList.value.findIndex(i => i.id == val)
      let a = actionList.value[actionActiveIndex.value]
      if (a) {
        formDataAction.value = a
      }
    },
    {
      immediate: true
    }
  )

  return {
    actionList,
    addAction,
    deleteAction,
    selectActionItem,
    resetActionForm,
    actionItemActive,
    actionFormRef,
    formDataAction,
    actionFormRules,
    actionActiveIndex
  }
}
